<template>
  <view class="container">
    <Card class="goal-card">
      <view class="goal-header">
        <text class="goal-title">{{ goal.title }}</text>
        <view class="goal-status" :class="goal.statusClass">
          {{ goal.status }}
        </view>
      </view>
      
      <!-- 概览信息 -->
      <view class="goal-info">
        <view class="info-item">
          <text class="label">目标类型：</text>
          <text class="value">{{ goal.typeLabel }}</text>
        </view>
        <view class="info-item">
          <text class="label">时间范围：</text>
          <text class="value">{{ goal.startTime }} - {{ goal.targetDate }}</text>
        </view>
        <view class="info-item info-item-desc" v-if="goal.description">
          <text class="label">目标描述：</text>
          <text :class="['value', 'multiline', { expanded: descExpanded }]">{{ goal.description }}</text>
        </view>
        <view class="desc-toggle" v-if="goal.description && shouldShowDescToggle" @click="toggleDesc">
          <text class="toggle-text">{{ descExpanded ? '收起' : '展开' }}</text>
        </view>
        <view class="info-item" v-if="isLearningGoal">
          <text class="label">目标分数：</text>
          <text class="value">{{ goal.targetScore || '-' }}</text>
        </view>
        <view class="info-item" v-if="goal.createTime">
          <text class="label">创建时间：</text>
          <text class="value">{{ goal.createTime }}</text>
        </view>
        <view class="info-item" v-if="goal.updateTime">
          <text class="label">最后更新：</text>
          <text class="value">{{ goal.updateTime }}</text>
        </view>
      </view>

      <!-- 子目标列表（对齐学习目标风格） -->
      <view class="subgoals-section" v-if="displaySubGoals.length > 0">
        <text class="subgoals-title">子目标（{{ displaySubGoals.length }}）</text>
        <view class="subgoals-list">
          <view 
            v-for="(subGoal, index) in displaySubGoals" 
            :key="subGoal.id || index" 
            class="subgoal-item"
          >
            <view class="subgoal-header">
              <text class="subgoal-name">{{ subGoal.name }}</text>
              <view class="subgoal-status" :class="subGoal.statusClass">{{ subGoal.status }}</view>
            </view>
            
            <view class="subgoal-info">
              <view class="subinfo-item">
                <text class="sublabel">时间范围：</text>
                <text class="subvalue">{{ subGoal.timeRange }}</text>
              </view>
              
              <view class="subinfo-item">
                <text class="sublabel">进度：</text>
                <text class="subvalue">{{ subGoal.progress }}%</text>
              </view>
              
              <view class="subinfo-item">
                <text class="sublabel">关联计划：</text>
                <text class="subvalue">{{ subGoal.planCount || 0 }}个</text>
              </view>
            </view>
            
            <view class="subgoal-progress-bar">
              <view class="subprogress-fill" :style="{ width: subGoal.progress + '%' }"></view>
            </view>
          </view>
        </view>
      </view>
      <view class="no-subgoals" v-else>
        <text>暂无子目标</text>
      </view>

      <!-- 总体进度 -->
      <Card class="overview-card">
        <view class="overview-header">
          <text class="overview-title">总体进度</text>
          <text class="overview-percentage">{{ overallProgress }}%</text>
        </view>
        <view class="overall-bar">
          <view class="overall-fill" :style="{ width: overallProgress + '%' }"></view>
        </view>
      </Card>
    </Card>
    
    <Card class="criteria-card">
      <view class="card-header">
        <text class="card-title">目标达成标准</text>
        <Button class="edit-btn" type="info" size="small" text="编辑" @click="goToEdit" />
      </view>
      <text class="criteria">{{ goal.criteria }}</text>
    </Card>
    
    <Card class="progress-card">
      <view class="card-header">
        <text class="card-title">进度记录</text>
      </view>
      
      <view class="progress-list">
        <view 
          v-for="(record, index) in goal.progressRecords" 
          :key="index" 
          class="progress-item"
        >
          <view class="record-header">
            <text class="record-date">{{ record.date }}</text>
            <view class="record-status" :class="record.statusClass">
              {{ record.status }}
            </view>
          </view>
          <text class="record-content">{{ record.content }}</text>
        </view>
      </view>
    </Card>
    
    
    
    <!-- 底部操作按钮（对齐学习目标页面样式） -->
    <view class="bottom-actions">
      <view class="secondary-actions">
        <Button class="secondary-btn" type="default" text="添加运动记录" @click="addProgress" />
      </view>
      <Button class="success-btn" type="success" text="确认目标达成" @click="confirmGoalCompletion" />
      <Button class="delete-btn" type="error" text="删除目标" @click="handleDelete" />
    </view>
  </view>
</template>

<script>
import { services } from '../../api/index.js';
const goalAPI = services.goal;

export default {
  data() {
    return {
      goalId: '',
      loading: false,
      descExpanded: false,
      goal: {
        id: '',
        title: '',
        student: '-',
        typeLabel: '运动目标',
        goalType: '',
        createTime: '',
        startTime: '',
        targetDate: '',
        updateTime: '',
        status: '',
        statusClass: '',
        targetScore: '',
        criteria: '',
        description: '',
        progressRecords: [],
        subGoals: []
      }
    };
  },
  async onLoad(options) {
    this.goalId = options?.id || '';
    if (this.goalId) {
      await this.fetchGoalDetail();
    }
  },
  computed: {
    isLearningGoal() {
      const t = this.goal?.goalType;
      return t === '1' || t === 1;
    },
    completedSubGoals() {
      const list = this.goal?.subGoals || [];
      return list.filter(g => (g.status === '已完成') || (Number(g.completionRate) >= 100)).length;
    },
    averageSubGoalProgress() {
      const list = this.goal?.subGoals || [];
      if (!list.length) return 0;
      const avg = list.reduce((sum, g) => sum + (Number(g.completionRate) || 0), 0) / list.length;
      return Math.round(avg);
    },
    overallProgress() {
      const goals = this.goal?.subGoals || [];
      if (!goals.length) return 0;
      const totalWeight = goals.reduce((sum, g) => sum + (Number(g.weight) || 0), 0) || 0;
      if (totalWeight > 0) {
        const weighted = goals.reduce((sum, g) => sum + ((Number(g.completionRate) || 0) * (Number(g.weight) || 0)), 0);
        return Math.round((weighted / totalWeight));
      }
      const avg = goals.reduce((sum, g) => sum + (Number(g.completionRate) || 0), 0) / goals.length;
      return Math.round(avg || 0);
    },
    shouldShowDescToggle() {
      // 简单依据长度判断是否需要展开/收起按钮
      if (!this.goal?.description) return false;
      return String(this.goal.description).length > 40; // 超过40字符提供折叠
    },
    displaySubGoals() {
      const list = this.goal?.subGoals || [];
      return list.map(sg => ({
        id: sg.id,
        name: sg.description || '-',
        timeRange: `${this.goal.startTime || ''} - ${this.goal.targetDate || ''}`,
        progress: Number(sg.completionRate || 0),
        planCount: Number(sg.planCount || 0),
        status: sg.status,
        statusClass: sg.statusClass
      }));
    }
  },
  
  methods: {
    confirmGoalCompletion() {
      uni.showModal({
        title: '确认目标达成',
        content: '确定这个目标已经达成了吗？确认后将无法撤销。',
        success: (res) => {
          if (res.confirm) {
            uni.showToast({ title: '目标已标记为达成', icon: 'success' });
          }
        }
      });
    },
    toggleDesc() {
      this.descExpanded = !this.descExpanded;
    },
    async fetchGoalDetail() {
      try {
        this.loading = true;
        uni.showLoading({ title: '加载中...' });
        const resp = await goalAPI.getGoalDetail(this.goalId);
        const data = resp?.data || resp || {};
        const mapStatus = s => s === 'PENDING' ? '未开始' : (s === 'IN_PROGRESS' ? '进行中' : (s === 'COMPLETED' ? '已完成' : (s || '-')));
        const mapClass = s => s === 'PENDING' ? 'status-pending' : (s === 'IN_PROGRESS' ? 'status-progress' : (s === 'COMPLETED' ? 'status-completed' : ''));
        const subGoals = Array.isArray(data.subGoals) ? data.subGoals : [];
        this.goal = {
          id: data.id || '',
          title: data.title || '',
          student: '-',
          goalType: data.goalType,
          typeLabel: (data.goalType === '1' || data.goalType === 1) ? '学习目标' : ((data.goalType === '2' || data.goalType === 2) ? '运动目标' : ((data.goalType === '3' || data.goalType === 3) ? '计划目标' : '目标')),
          createTime: '',
          startTime: data.startTime || '',
          targetDate: data.deadline || '',
          updateTime: '',
          status: mapStatus(data.status),
          statusClass: mapClass(data.status),
          targetScore: data.targetScore ?? '',
          criteria: '',
          description: data.description || '',
          progressRecords: [],
          subGoals: subGoals.map(sg => ({
            id: sg.id,
            description: sg.description || '',
            priority: sg.priority || '',
            completionRate: Number(sg.completionRate ?? 0),
            weight: Number(sg.weight ?? 0),
            planCount: Number(sg.planCount ?? 0),
            status: mapStatus(sg.status),
            statusClass: mapClass(sg.status)
          }))
        };
      } catch (e) {
        uni.showToast({ title: '加载失败', icon: 'none' });
      } finally {
        this.loading = false;
        uni.hideLoading();
      }
    },
    goToEdit() {
      uni.navigateTo({
        url: '/pages/goal/edit-life?id=' + this.goal.id
      });
    },
    
    addProgress() {
      uni.navigateTo({
        url: '/pages/goal/add-record'
      });
    },
    
    handleDelete() {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个生活目标吗？此操作不可恢复。',
        success: (res) => {
          if (res.confirm) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            });
            
            // 返回目标列表
            setTimeout(() => {
              uni.navigateBack();
            }, 1000);
          }
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
// 本文件本地使用的颜色变量（避免未定义报错）
$success-color: #33CC99;
$danger-color: #FF6666;
$warning-color: #FFCC33;
.container {
  padding: $spacing-base;
  background-color: $background-color;
  min-height: 100vh;
}

.goal-card {
  margin-bottom: $spacing-base;
}

.goal-header {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  margin-bottom: $spacing-lg;
}

.goal-title {
  font-size: $font-size-lg;
  font-weight: bold;
  color: $text-primary;
  flex: 1;
}

.goal-status {
  font-size: $font-size-sm;
  padding: $spacing-xs $spacing-sm;
  border-radius: $border-radius-sm;
}

.status-progress {
  background-color: rgba($primary-color, 0.1);
  color: $primary-color;
}

.goal-info {
  font-size: $font-size-sm;
}

.info-item {
  display: flex;
  flex-direction: row;
  margin-bottom: $spacing-sm;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.label { color: $text-secondary; width: 160rpx; font-size: $font-size-sm; }

.value { flex: 1; color: $text-primary; font-size: $font-size-sm; }

.criteria-card, .progress-card, .description-card {
  margin-bottom: $spacing-base;
}

/* 概览卡片 */
.overview-card {
  margin-top: $spacing-lg;
  margin-bottom: $spacing-base;
}
.overview-header {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  margin-bottom: $spacing-sm;
}
.overview-title { font-size: $font-size-base; font-weight: bold; color: $text-primary; }
.overview-percentage { color: $primary-color; font-weight: bold; }
.overall-bar {
  width: 100%;
  height: 16rpx;
  background-color: $background-color;
  border-radius: 8rpx;
  overflow: hidden;
}
.overall-fill {
  height: 100%;
  background: linear-gradient(90deg, $secondary-color, $primary-color);
  border-radius: 8rpx;
  transition: width 0.6s ease;
}

.card-header {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  margin-bottom: $spacing-base;
}

.card-title {
  font-size: $font-size-base;
  font-weight: bold;
  color: $text-primary;
}

.subgoals-summary { display: flex; align-items: center; gap: $spacing-sm; color: $text-secondary; font-size: $font-size-sm; }
.divider { color: $text-tertiary; }

.criteria, .description,
.multiline {
  font-size: $font-size-base;
  color: $text-primary;
  line-height: 1.6;
}

.info-item-desc .value.multiline { white-space: pre-wrap; display: -webkit-box; -webkit-line-clamp: 2; line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
.info-item-desc .value.multiline.expanded { -webkit-line-clamp: unset; line-clamp: unset; display: block; }
.desc-toggle { margin-top: 6rpx; }
.toggle-text { color: $primary-color; font-size: $font-size-sm; }

.progress-list { margin-top: $spacing-sm; }

/* 子目标区域（对齐学习页） */
.subgoals-section {
  width: 100%;
  box-sizing: border-box;
  margin-top: $spacing-base;
  padding-top: $spacing-base;
  border-top: 1rpx solid $border-color;
}

.subgoals-title {
  font-size: $font-size-base;
  font-weight: bold;
  color: $text-primary;
  margin-bottom: $spacing-sm;
  display: block;
}

.subgoals-list {
  width: 100%;
  box-sizing: border-box;
}

/* 子目标卡片整体与上下内容的间距 */


.subgoal-item {
  background-color: rgba($background-color, 0.7);
  border-radius: $border-radius-base;
  padding: $spacing-base;
  margin-bottom: $spacing-sm;
  width: 100%;
  box-sizing: border-box;
  transition: all 0.3s ease;
  &:last-child { margin-bottom: 0; }
}

.subgoal-item:active {
  background-color: $background-color;
  transform: scale(0.98);
}

.subgoal-header { display: flex; flex-direction: row; align-items: center; justify-content: space-between; margin-bottom: $spacing-sm; }
.subgoal-name { font-size: $font-size-base; font-weight: bold; color: $text-primary; flex: 1; padding-right: $spacing-sm; }
.subgoal-status { font-size: $font-size-sm; padding: $spacing-xs $spacing-sm; border-radius: $border-radius-sm; }

.subgoal-info { font-size: $font-size-sm; width: 100%; box-sizing: border-box; margin-bottom: $spacing-sm; }
.subinfo-item { display: flex; flex-direction: row; margin-bottom: $spacing-xs; width: 100%; box-sizing: border-box; }
.sublabel { color: $text-secondary; width: 140rpx; flex-shrink: 0; }
.subvalue { flex: 1; color: $text-primary; }

.subgoal-progress-bar { width: 100%; height: 16rpx; background-color: $background-color; border-radius: 9999rpx; overflow: hidden; box-sizing: border-box; }
.subprogress-fill { height: 100%; background: linear-gradient(90deg, $secondary-color, $primary-color); border-radius: 8rpx; transition: width 0.6s ease; }

.status-improved {
  background-color: rgba($secondary-color, 0.1);
  color: $secondary-color;
}

.status-trying {
  background-color: rgba($warning-color, 0.1);
  color: $warning-color;
}

/* 状态颜色（对齐学习页） */
.status-completed { background-color: rgba($success-color, 0.1); color: $success-color; }
.status-pending { background-color: rgba($warning-color, 0.1); color: $warning-color; }

.record-content {
  font-size: $font-size-base;
  color: $text-primary;
  line-height: 1.5;
}

/* 底部操作按钮（参考学习目标样式） */
.bottom-actions {
  width: 100%;
  box-sizing: border-box;
  padding: $spacing-lg 0 $spacing-xl 0;
  display: flex;
  flex-direction: column;
  gap: $spacing-lg;
}

.secondary-actions { display: flex; flex-direction: row; gap: $spacing-base; width: 100%; box-sizing: border-box; }
.secondary-btn {
  flex: 1;
  min-height: 88rpx;
  height: 88rpx;
  line-height: 88rpx;
  font-size: $font-size-base;
  border-radius: $border-radius-lg;
  border: 1px solid $border-color;
  background-color: white;
  color: $text-primary;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.success-btn {
  min-height: 64rpx; height: 64rpx; line-height: 64rpx; font-size:16px; font-weight: 500; border-radius: $border-radius-lg; background-color: $success-color; color: white; border: none; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); box-shadow: 0 4rpx 12rpx rgba(73, 194, 163, 0.3); overflow: hidden; position: relative;
}

.delete-btn { min-height: 64rpx; height: 64rpx; line-height: 64rpx; font-size: $font-size-base; border-radius: $border-radius-lg; background-color: $danger-color; color: white; border: none; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); }
</style>